package com.example.security.config;

import com.example.security.filter.JwtLoginFilter;
import com.example.security.service.MyAccessDeniedHandler;
import com.example.security.service.MyAuthenticationEntryPoint;
import com.example.security.service.MyUserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;


/**
 * @author chenjf
 * @Date 2022/9/19
 * @Description security配置类
 */
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)//开启权限注解
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyAuthenticationEntryPoint myAuthenticationEntryPoint;//认证失败处理类
    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;//授权失败处理类
    @Autowired
    private MyUserDetailsServiceImpl myUserDetailsServiceImpl;//自定义UserDetailsService
    @Autowired
    private JwtLoginFilter jwtLoginFilter;//自定义jwt过滤器


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .csrf().disable()//关闭跨站请求伪造
                .headers().frameOptions().disable()//关闭网页嵌入安全检查【解决前端报错X-Frame-Options】允许使用内嵌网页iframe
//                .and()
//                .cors().configurationSource(configurationSource())//处理前后端请求跨域
        ;

        //接口请求处理
        http.authorizeRequests()
                .antMatchers("/login", "/register","/captcha").anonymous()//对登录注册进行放行
                .antMatchers("/modeler/**").anonymous()
                .antMatchers("/email/send").anonymous()
                .antMatchers(
                        HttpMethod.GET,
                        "/",
                        "/*.html",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js",
                        "/profile/**").permitAll()//对静态页面进行放行
                .antMatchers("/sys/generator/**").permitAll()//对代码生成器放行
                .antMatchers("/test/**").permitAll()//对测试接口进行放行
                .anyRequest().authenticated()//对除上面所有请求进行拦截
        ;

        //认证与授权异常处理
        http.exceptionHandling()
                .authenticationEntryPoint(myAuthenticationEntryPoint)//对未认证的请求进行返回设置
                .accessDeniedHandler(myAccessDeniedHandler)//对未经过授权的请求进行返回配置
        ;

        //自定义jwt过滤器
        http.addFilterBefore(jwtLoginFilter, UsernamePasswordAuthenticationFilter.class);
        // 添加CORS filter
        http.addFilterBefore(corsFilter(), JwtLoginFilter.class);
        http.addFilterBefore(corsFilter(), LogoutFilter.class);
    }

    //1.自定义AuthenticationManager  推荐  并没有在工厂中暴露出来
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsServiceImpl);
    }

    //2.作用: 用来将自定义AuthenticationManager在工厂中进行暴露,可以在任何位置注入
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 解决跨域
     *
     * @return
     */
//    @Bean
//    CorsConfigurationSource configurationSource() {
//        CorsConfiguration corsConfiguration = new CorsConfiguration();
//        corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
//        corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
//        corsConfiguration.setAllowedOrigins(Arrays.asList("*"));
//        corsConfiguration.setAllowCredentials(true);
//        corsConfiguration.setMaxAge(3600L);
//        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//        source.registerCorsConfiguration("/**", corsConfiguration);
//        return source;
//    }

    @Bean
    public CorsFilter corsFilter()
    {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 设置访问源地址
        config.addAllowedOriginPattern("*");
        // 设置访问源请求头
        config.addAllowedHeader("*");
        // 设置访问源请求方法
        config.addAllowedMethod("*");
        // 对接口配置跨域设置
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}
